package online.struts.chain.command;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.ServletException;

import online.struts.action.UniForm;
import online.struts.chain.command.ActionRequest.CommandRequest;
import online.struts.mapping.RequestMapping;

import org.apache.logging.log4j.LogManager;
import org.apache.struts.chain.commands.ActionCommandBase;
import org.apache.struts.chain.contexts.ActionContext;
import org.apache.struts.chain.contexts.ServletActionContext;
import org.apache.struts.config.ForwardConfig;

/**
 * インクルードプロセッサ
 *
 * @author Tadashi Nakayama
 */
public final class IncludeProcessor extends ActionCommandBase implements CommandRequest {

	/**
	 * @see org.apache.struts.chain.commands.ActionCommandBase
	 * #execute(org.apache.struts.chain.contexts.ActionContext)
	 */
	@Override
	public boolean execute(final ActionContext context) throws Exception {
		return ActionRequest.execute(context, this);
	}

	/**
	 * @see online.struts.chain.command.ActionRequest.CommandRequest
	 * #command(org.apache.struts.chain.contexts.ServletActionContext,
	 * online.struts.mapping.RequestMapping, online.struts.action.UniForm)
	 */
	@Override
	public boolean command(final ServletActionContext sac,
			final RequestMapping mapping, final UniForm uf) {

		if (sac.getResponse().isCommitted() || sac.getForwardConfig() == null) {
			return false;
		}

		ForwardConfig fc = sac.getForwardConfig();
		if (Objects.toString(fc.getPath(), "").isEmpty()) {
			return false;
		}

		try {
			sac.getContext().getRequestDispatcher(
					fc.getPath()).include(sac.getRequest(), sac.getResponse());
		} catch (ServletException e) {
			LogManager.getLogger().warn(e.getMessage(), e);
		} catch (IOException e) {
			LogManager.getLogger().info(e.getMessage());
		}
		return true;
	}
}
